/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao.basedato;

import java.sql.*;

/**
 *
 * @author vyamunaque
 */
public class DAOOperaciones {

    public Object[][] selectData(String tabla, String campos, String condiciones, Connection cnx) throws Exception {
        int registros = 0;
        String colNombre[] = campos.split(",");
        String strSQL = " SELECT " + campos + " FROM " + tabla;
        String strSQL2 = " SELECT count(*) as cantRegistros FROM " + tabla;
        if (condiciones != null) {
            strSQL += " WHERE " + condiciones;
            strSQL2 += " WHERE " + condiciones;
        }
        try {
            PreparedStatement pst = cnx.prepareStatement(strSQL2);
            ResultSet res = pst.executeQuery();
            res.next();
            registros = res.getInt("cantRegistros");
            res.close();
        } catch (SQLException ex) {
            throw new Exception(ex.getMessage());
        }
        // se crea matriz con tantas filas y columnas que necesitamos
        Object[][] datos = new String[registros][campos.split(",").length];
        try {
            PreparedStatement pst = cnx.prepareStatement(strSQL);
            ResultSet res = pst.executeQuery();
            int i = 0;
            while (res.next()) {
                for (int j = 0; j <= campos.split(",").length - 1; j++) {
                    datos[i][j] = res.getString(colNombre[j].trim());
                }
                i++;
            }
            res.close();
        } catch (SQLException ex) {
            throw new Exception(ex.getMessage());
           // System.out.println(ex);
        }
        return datos;
    }
    
    public boolean insertData(String tabla, String campos, String valores, Connection cnx) throws Exception{
        boolean res=false;
        String strSQL=" INSERT INTO "+tabla+" ( "+campos+" ) VALUES ( "+valores+" )";
        try{
            PreparedStatement pst = cnx.prepareStatement(strSQL);
            pst.execute();
            pst.close();
            res=true;
            System.out.println("Registrado Correctamente");
        } catch (SQLException ex) {
            throw new Exception(ex.getMessage());           
        }
        return res;
    }


            
     public int ultimoID(String tabla, String campo, Connection cnx) throws Exception{
        int ultID=0;
        String strSQL = " SELECT max("+campo+") as Ultimo FROM " + tabla;
        try{           
            PreparedStatement pst = cnx.prepareStatement(strSQL);
            ResultSet res = pst.executeQuery();
            res.first();
            ultID = res.getInt("Ultimo");
            res.close();
            pst.close();
        } catch (SQLException ex) {
            throw new Exception(ex.getMessage());           
        }
        return ultID;
    }
}
